/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.action;

import com.jspx.boot.EnvFactory;
import com.jspx.boot.environment.Environment;
import com.jspx.boot.sign.LanguageRes;
import com.jspx.sioc.BeanFactory;
import com.jspx.sober.Transaction;
import com.jspx.sober.exception.TransactionException;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.dao.PermissionDAO;
import com.jspx.txweb.env.TXWebIoc;
import com.jspx.txweb.table.Role;
import com.jspx.txweb.table.TreeItem;
import com.jspx.txweb.table.TreeRole;
import com.jspx.txweb.view.TreeView;
import com.jspx.scriptmark.XmlEngine;
import com.jspx.scriptmark.core.TagNode;
import com.jspx.scriptmark.parse.XmlEngineImpl;
import com.jspx.scriptmark.parse.html.NodeTag;
import com.jspx.txweb.IUserSession;
import com.jspx.utils.*;
import com.jspx.txweb.annotation.Operate;
import com.jspx.zhex.spell.ChineseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2008-9-24
 * Time: 15:20:38
 */
@HttpMethod(caption = "栏目树", location = "[\\w+tree|tree\\S*]")
public class TreeManageAction extends TreeView {
    final private static Logger log = LoggerFactory.getLogger(TreeManageAction.class);
    private long id = 0;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
    private String treeValue = StringUtil.empty;
    public String getTreeValue() {
        return treeValue;
    }

    public void setTreeValue(String treeValue) {
        this.treeValue = treeValue;
    }

    public TreeManageAction() {

    }

    private boolean checkNodeId() {
        if (StringUtil.isNULL(nodeId)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.invalidParameter));
            return false;
        }
        return true;
    }

    private boolean checkCaption() throws Exception {
        if (StringUtil.isNULL(getString("caption", true))) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.nodeNameNeedInput));
            return false;
        }
        return true;
    }

    @Operate(caption = "清空缓存")
    public void clear() throws Exception
    {
        setActionResult(ROC);
        treeItemDAO.evict(TreeItem.class);
        addActionMessage(language.getLang(LanguageRes.operationSuccess));
    }

    @Operate(caption = "添加节点")
    public void addTreeItem() throws Exception
    {
        TreeItem treeItem = (TreeItem) getBean(TreeItem.class);
        IUserSession userSession = (IUserSession) getUserSession();
        treeItem.setPutUid(userSession.getUid());
        treeItem.setPutName(userSession.getName());

        //得到简拼begin
        treeItem.setSpelling(ChineseUtil.getFullSpell(treeItem.getCaption(), ""));
        //得到简拼end

        if (treeItemDAO.addTreeItem(getFirstNodeId(), treeItem)) {
            addActionMessage(language.getLang(LanguageRes.saveSuccess));
            setActionResult(SUCCESS);
        }
    }

    @Operate(caption = "添加子节点")
    public void addChildTreeItem() throws Exception {
        if (!checkNodeId()) return;
        if (!checkCaption()) return;
        TreeItem treeItem = (TreeItem) getBean(TreeItem.class);
        IUserSession userSession = (IUserSession) getUserSession();
        treeItem.setPutName(userSession.getName());
        treeItem.setPutUid(userSession.getUid());
        //得到简拼begin
        treeItem.setSpelling(ChineseUtil.getFullSpell(treeItem.getCaption(), ""));
        //得到简拼end
        if (treeItemDAO.addChildTreeItem(getFirstNodeId(), treeItem)) {
            addActionMessage(language.getLang(LanguageRes.addChildNodeSuccess));
            setActionResult(SUCCESS);
        } else addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.deleteFailure));
    }

    @Operate(caption = "删除节点")
    public void deleteTreeItem() throws Exception
    {
        if (!checkNodeId()) return;
        if (treeItemDAO.deleteTreeItem(getFirstNodeId())) {
            addActionMessage(language.getLang(LanguageRes.deleteSuccess));
            setActionResult(SUCCESS);
        } else addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.deleteFailure));
    }

    @Operate(caption = "编辑节点")
    public void editTreeItem() throws Exception
    {
        if (isGuest()) return;
        String nodeId = getNodeId();
        TreeItem treeItemOld = null;

        if (id > 0)
            treeItemOld = (TreeItem) treeItemDAO.get(TreeItem.class, id);
        else if (!StringUtil.isNULL(nodeId))
            treeItemOld = treeItemDAO.getTreeItem(nodeId);
        if (treeItemOld == null) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.invalidParameter));
            return;
        }

        IUserSession userSession = (IUserSession) getUserSession();
        TreeItem treeItem = (TreeItem) getBean(TreeItem.class);
        treeItem.setNodeId(getFirstNodeId());
        treeItem.setPutName(userSession.getName());
        treeItem.setPutUid(userSession.getUid());
        treeItem.setId(treeItemOld.getId());
        treeItem.setNamespace(treeItemOld.getNamespace());
        treeItem.setCreateDate(treeItemOld.getCreateDate());
        treeItem.setParentNodeId(treeItemOld.getParentNodeId());
        //得到简拼begin
        treeItem.setSpelling(ChineseUtil.getFullSpell(treeItem.getCaption(), ""));
        //得到简拼end
        if (treeItemDAO.editTreeItem(treeItem)) {
            addActionMessage(language.getLang(LanguageRes.updateSuccess));
            setActionResult(SUCCESS);
        } else addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.updateFailure));
    }


    @Operate(caption = "保存XML列表")
    public void saveXml() throws Exception
    {
        IUserSession userSession = (IUserSession) getUserSession();
        if (userSession == null || userSession.isGuest()) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needLogin));
            setActionResult(LOGIN);
            return;
        }

        if (StringUtil.isNULL(treeValue)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.notDataFind));
            return;
        }
        setActionLogContent(treeValue);

        List<TreeItem> saveList = new LinkedList<TreeItem>();
        XmlEngine xmlEngine = new XmlEngineImpl();
        xmlEngine.putTag("node", NodeTag.class.getName());
        List<TagNode> tagList = xmlEngine.getTagNodes(treeValue);
        for (TagNode node : tagList) {
            NodeTag nodeTag = (NodeTag) node;
            TreeItem treeItem = new TreeItem();
            treeItem.setNodeId(XMLUtil.deleteQuote(nodeTag.getAttribute("id")));
            TreeItem oldTreeItem = treeItemDAO.getTreeItem(treeItem.getNodeId());
            if (oldTreeItem != null) BeanUtil.copySimpleProperty(treeItem, oldTreeItem);
            treeItem.setCaption(XMLUtil.deleteQuote(nodeTag.getAttribute("text")));
            //得到简拼begin
            treeItem.setSpelling(ChineseUtil.getFullSpell(treeItem.getCaption(), ""));
            //得到简拼end
            treeItem.setParentNodeId(XMLUtil.deleteQuote(nodeTag.getAttribute("pid")));
            treeItem.setIcon(XMLUtil.deleteQuote(nodeTag.getAttribute("icon")));
            treeItem.setOpenIcon(XMLUtil.deleteQuote(nodeTag.getAttribute("openIcon")));
            treeItem.setSortType(StringUtil.toInt(XMLUtil.deleteQuote(nodeTag.getAttribute("sort"))));
            treeItem.setNamespace(treeItemDAO.getNamespace());
            treeItem.setPutName(userSession.getName());
            treeItem.setPutUid(userSession.getUid());
            saveList.add(treeItem);
        }

        //ID有可能会重复,需要检查后在保存 begin
        String[] idArray = null;
        for (TreeItem treeItem : saveList) {
            if (StringUtil.isNULL(treeItem.getNodeId())) {
                addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.notAllowedSaveNullNodeId));
                return;
            }
            if (!ArrayUtil.inArray(idArray, treeItem.getNodeId(), true))
                idArray = ArrayUtil.add(idArray, treeItem.getNodeId());
            else {
                addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.notAllowedSaveRepeatNodeId) + ":" + treeItem.getNodeId() + " " + treeItem.getCaption());
                return;
            }
        }
        //ID有可能会重复,需要检查后在保存 end
        if (saveList.isEmpty()) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.notDataFind));
            return;
        }
        try {
            if (treeItemDAO.deleteTree())
            {
                int i = treeItemDAO.save(saveList);
                if (i > 0) {
                    addActionMessage(language.getLang(LanguageRes.saveSuccess) + ":" + i);
                }
            }
            setActionResult(SUCCESS);
        } catch (Exception e) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.updateFailure));
        }
    }

    /**
     * 更新用户角色浏览权限，每次编辑树结构后都需要重新生成
     * @throws SQLException
     * @throws TransactionException
     */
    private void updateTreeRoles() throws SQLException, TransactionException {
        BeanFactory beanFactory = EnvFactory.getBeanFactory();
        PermissionDAO permissionDAO = (PermissionDAO)beanFactory.getBean(TXWebIoc.permissionDAO,treeItemDAO.getNamespace());
        List<Role> roleList = permissionDAO.getRoleList();
        List<TreeItem> treeItemList = treeItemDAO.createRepairTreeRole(roleList);
        Collection<TreeRole> treeRoleList = treeItemDAO.createTreeRole(treeItemList,roleList);
        Transaction transaction = treeItemDAO.createTransaction();
        try
        {
            transaction.begin();
            treeItemDAO.deleteTreeRole();
            treeItemDAO.save(treeRoleList);
            transaction.commit();
            treeItemDAO.evict(TreeRole.class);
        } catch (Exception e)
        {
            transaction.rollback();
            log.error("保存树权限发送错误",e);
        } finally {
            treeRoleList.clear();
        }
    }

    public String execute() throws Exception {
        if (isMethodInvoked()) {
            treeItemDAO.evict(TreeItem.class);
            updateTreeRoles();
        }
        return super.execute();
    }
}